package com.wgt.startx.util;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * smartClassLoader类加载器的工具类
 * 提供类操作相关的方法如：获取类加载器、加载类、获取指定包名下的所有类等。
 * Created by wgt on 2017/7/29.
 */
public final class SmartClassUtil {
    private static final Logger log = LoggerFactory.getLogger(SmartClassUtil.class);

    /**
     * 获取当前线程的类加载器
     * @return
     */
    public static ClassLoader getClassLoader(){
        return Thread.currentThread().getContextClassLoader();
    }

    /**
     * 加载类
     * @param className
     * @param isInitialized
     * @return
     */
    public static Class<?> loadClass(String className, boolean isInitialized){
        Class<?> cls;
        try {
            cls = Class.forName(className,isInitialized,getClassLoader());
        }catch (ClassNotFoundException e) {
            log.error("class loaded failure:{}",e);
            throw new RuntimeException(e);
        }
        return cls;
    }


    /**
     * 获取指定包下的集合
     * @param packageName 包名
     * @return
     */
    public static Set<Class<?>> getClassSet(String packageName){
        Set<Class<?>> classSet = new HashSet<Class<?>>();
        try {
            Enumeration<URL> urls = getClassLoader().getResources(packageName.replace(".","/"));
            while(urls.hasMoreElements()){
                URL url = urls.nextElement();
                if (url!=null){
                    String protocaol = url.getProtocol();
                    log.info("resource url protocol:{}",protocaol);
                    if ("file".equals(protocaol)){
                        String packagePath = url.getPath().replace("%20"," ");
                        packagePath = packagePath.substring(1,packagePath.length());
                        addClass(classSet,packagePath,packageName);
                    }
                    if ("jar".equals(protocaol)){
                        JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
                        if (jarURLConnection != null){
                            JarFile jarFile = jarURLConnection.getJarFile();
                            if (jarFile!=null){
                                Enumeration<JarEntry> jaree = jarFile.entries();
                                while (jaree.hasMoreElements()){
                                    JarEntry je = jaree.nextElement();
                                    String jarName = je.getName();
                                    if (jarName.endsWith(".class")){
                                        String className = jarName.substring(0,jarName.lastIndexOf(".")).replace("/",".");
                                        doaddClass(classSet,className);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (IOException e) {
            log.error("get class Set failure:"+packageName,e);
            throw new RuntimeException(e);
        }
        return classSet;
    }

    /**
     *组合包名，添加class到set集合中
     * @param classSet
     * @param packagePath
     * @param packageName
     */
    public static void addClass(Set<Class<?>> classSet, String packagePath, String packageName) {
        File[] files = new File(packagePath).listFiles(new FileFilter() {
            public boolean accept(File pathname) {
                return (pathname.isFile()&&pathname.getName().endsWith(".class"))||pathname.isDirectory();
            }
        });
        for (File file :files){
            String filename = file.getName();
            if (file.isFile()) {
                String className = filename.substring(0, filename.lastIndexOf("."));
                if (StringUtils.isNotEmpty(packageName)) {
                    className = packageName + "." + className;
                    doaddClass(classSet, className);
                }
            }else{
                // 获取子包
                String subPackagePath = filename;
                if (StringUtils.isNotEmpty(packagePath)) {
                    subPackagePath = packagePath + "/" + subPackagePath;
                }
                // 子包名
                String subPackageName = filename;
                if (StringUtils.isNotEmpty(packageName)) {
                    subPackageName = packageName + "." + subPackageName;
                }
                // 递归调用
                addClass(classSet, subPackagePath, subPackageName);
            }

        }

    }

    /**
     * 添加class到集合
     * @param classSet
     * @param className
     */
    public static void doaddClass(Set<Class<?>> classSet, String className) {
        Class<?> cls = loadClass(className,false);
        classSet.add(cls);
    }
}
